import router from './router/index'
import store from './store/index'
import { getToken, getRoles, setRoles, getUserName, setUserName } from '@/utils/store'
import { getUserById } from '@/api/user'
router.beforeEach((to, from, next) => {
    const token = getToken()
    if (token) {
        if (to.path == '/login') {
            next("/")
        } else {
            // 检查是否有用户角色信息
            const hasRoles = getRoles() && getRoles().length > 0
            if (hasRoles) {
                next()
            } else {
                // 获取用户信息
                getUserById(token).then(res => {
                    setUserName(res.data.realName)
                    setRoles(res.data.roles)
                })
            }

            // 生成路由
            store.dispatch("GenerateRoutes", getRoles()).then(res => {
                next()
            })
        }
    } else {
        if (to.path != '/login') {
            next("/login")
        } else {
            next()
        }
    }
})
